package com.example.demo;

import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.cache.CacheKey;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.ParameterMapping;
import org.apache.ibatis.mapping.SqlSource;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Signature;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.scripting.defaults.RawSqlSource;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;
import org.apache.ibatis.type.TypeHandlerRegistry;

import java.lang.reflect.Method;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Collection;
import java.util.Date;
import java.util.List;

@Intercepts({
        @Signature(
                type = Executor.class,
                method = "update",
                args = {MappedStatement.class, Object.class}),
        @Signature(
                type = Executor.class,
                method = "query",
                args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class, CacheKey.class, BoundSql.class}),
        @Signature(
                type = Executor.class,
                method = "query",
                args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class})
})
@Slf4j
public class MyBatisLogInterceptor implements Interceptor {
    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        Object target = invocation.getTarget();
        Object[] args = invocation.getArgs();
        Method method = invocation.getMethod();
        log.info("方法拦截器：{}", method);
        if (target instanceof Executor) {
            Object arg = args[1];
            MappedStatement mappedStatement = (MappedStatement) args[0];
            SqlSource sqlSource = mappedStatement.getSqlSource();
            if (sqlSource instanceof RawSqlSource) {
                RawSqlSource rawSqlSource = (RawSqlSource) sqlSource;
                BoundSql boundSql = rawSqlSource.getBoundSql(arg);
                String fullSql = genFullSql(mappedStatement, boundSql);
                // com.example.xbrother.mapper.MaterialMapper.getByCode
                log.info("【mapperId】mapperId = {}", mappedStatement.getId());
                // select id , code, name, model_type, specs, property, search_keys, price, unit, group_type, type, del_flag from t_material where del_flag = 0 and code = '1170250002441'
                log.info("【全量sql】RawSqlSource = {}", fullSql);
            }
        }

        return invocation.proceed();
    }

    /**
     * 格式化sql
     */
    private String sqlFormate(String srcSql) {
        return srcSql.replaceAll("[\\s]+", " ");
    }

    /**
     * 获取参数的string值
     */
    private String getParameterStringValue(Object obj) {
        String value = "";
        if (obj instanceof String) {
            value = "'" + obj.toString() + "'";
        } else if (obj instanceof Date) {
            // todo:
        } else if (obj instanceof LocalDateTime) {
            // todo:
        } else if (obj instanceof LocalDate) {
            // todo:
        } else if (obj instanceof Collection) {
            // todo:
        }
        return value;
    }

    private String genFullSql(MappedStatement mappedStatement, BoundSql boundSql) {
        Configuration configuration = mappedStatement.getConfiguration();
        List<ParameterMapping> parameterMappings = boundSql.getParameterMappings();
        Object parameterObject = boundSql.getParameterObject();
        // 格式化的sql: 带有占位符
        String sqlFormated = sqlFormate(boundSql.getSql());
        if (parameterMappings.size() > 0 && parameterObject != null) {
            TypeHandlerRegistry typeHandlerRegistry = configuration.getTypeHandlerRegistry();
            boolean isOneParam = typeHandlerRegistry.hasTypeHandler(parameterObject.getClass());
            if (isOneParam) {
                sqlFormated = sqlFormated.replaceAll("\\?", getParameterStringValue(parameterObject));
            } else {
                MetaObject metaObject = configuration.newMetaObject(parameterObject);
                for (ParameterMapping parameterMapping : parameterMappings) {
                    String parameterKey = parameterMapping.getProperty();
                    boolean hasField = metaObject.hasGetter(parameterKey);
                    if (hasField) {
                        sqlFormated = sqlFormated.replaceFirst("\\?", getParameterStringValue(metaObject.getValue(parameterKey)));
                    } else if (boundSql.hasAdditionalParameter(parameterKey)) {
                        sqlFormated = sqlFormated.replaceFirst("\\?", getParameterStringValue(boundSql.getAdditionalParameter(parameterKey)));
                    }
                }
            }
        }
        return sqlFormated;
    }
}
